<template>
	<el-main style="padding-top: 0">
		<el-form inline style="display: flex">
			<el-form-item v-if="secdLv.Options" label="二级分类">
				<el-input v-if="secdLv.InputType == '0'" v-model="params.ItemType" placeholder="请输入二级分类" clearable />
				<el-select v-else v-model="params.ItemType" placeholder="请输入二级分类" clearable>
					<el-option v-for="(item, index) in secdLv.Options" :key="index" :value="item.value" :label="item.label" />
				</el-select>
			</el-form-item>
			<el-form-item :label="parentData.Title">
				<el-input v-model="params.Title" :placeholder="'请输入' + parentData.Title" clearable />
			</el-form-item>
			<el-button type="primary" @click="queryTreeData">搜索</el-button>
		</el-form>
		<el-row style="height: 55px; display: flex; align-items: center; font-size: 18px">
			<el-page-header v-if="pageIndex" @back="goBack" />
			父节点：{{ parentData.Title }}
			<!-- <el-button type="primary" style="margin-left: 15px" @click="addSubNode">添加子节点</el-button> -->
			<el-button type="primary" style="margin-left: 15px" @click="addSubNode">添加{{ parentData.Title }}</el-button>
		</el-row>
		<el-table :data="treeList" border>
			<el-table-column label="层级" prop="Level" />
			<!-- <el-table-column label="节点编码" prop="ItemCode" /> -->
			<el-table-column :label="parentData.Title + '-节点编码'" prop="ItemCode" />
			<!-- <el-table-column label="一级节点" prop="Title" /> -->
			<el-table-column :label="parentData.Title" prop="Title" />
			<el-table-column label="图标" prop="IconID">
				<template #default="scope">
					<i v-if="/^el-.+/.test(scope.row.IconID)" :class="scope.row.IconID" style="font-size: 26px" />
					<img v-else-if="/^http.+/.test(scope.row.IconID)" :src="scope.row.IconID" style="width: 30px" />
				</template>
			</el-table-column>
			<el-table-column label="创建时间">
				<template #default="scope">
					{{ formatTime2View(scope.row.CreateTime) }}
				</template>
			</el-table-column>
			<el-table-column label="发布时间">
				<template #default="scope">
					{{ formatTime2View(scope.row.PublishTime) }}
				</template>
			</el-table-column>
			<el-table-column label="是否发布">
				<template #default="scope">
					<el-switch v-model="scope.row.Status" active-text="是" inactive-text="否" @change="(e) => release(e, scope.row)" />
				</template>
			</el-table-column>
			<el-table-column v-if="secdLv.Name" :label="secdLv.Name">
				<template #default="scope">
					{{ scope.row.secdLvLabel || '--' }}
				</template>
			</el-table-column>
			<template v-if="Extend.length">
				<el-table-column v-for="item in Extend" :key="item.key" :label="item.title">
					<template #default="scope">
						<template v-for="val in scope.row.ExtendContent" :key="'scope' + val.key">
							{{ val.key == item.key ? val.value : '' }}
						</template>
					</template>
				</el-table-column>
			</template>
			<el-table-column label="操作" width="180px">
				<template #default="scope">
					<span class="set" @click="updataNode(scope.row)">修改</span>
					<span v-if="Hierarchy && Hierarchy > scope.row.Level && pageIndex <= Hierarchy" class="set" @click="ManageSub(scope.row)">管理下级</span>
					<span class="set" @click="delNode(scope.row)">删除</span>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			:current-page="params.current"
			:page-sizes="[20, 30, 50, 100]"
			:page-size="params.limit"
			:total="params.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="handleSizeChange"
			@current-change="handleCurrentChange"
		/>
		<el-dialog v-if="showEdit" v-model="showEdit" :title="operation + '节点'" width="600px">
			<TreeForm
				:groupID="groupID"
				:parent-node="parentData"
				:cur-node="curNode"
				:secd-lv="secdLv"
				:extend="Extend"
				:operation="operation"
				:tree-type="treeType"
				:useIcon="useIcon"
				@hideEditFn="hideEditFn"
			/>
		</el-dialog>
	</el-main>
</template>

<script lang="js">
// import { Post } from '/@/api/linxyun/base/index.ts'
import { formatTime2View } from '/@/utils/formatTime.ts'
import TreeForm from './TreeForm.vue'
import { getLocalStorage, getVuex, getObjAttr } from '/@/utils/formatPrivacyData.js'

import { httpReqeustApi } from '/@/api/linxyun/base';

const httpReqeust = httpReqeustApi();

export default {
	name: 'ParentNode',

	components: { TreeForm },
	props: {
		treeType: String
	},
	data() {
		return {
			parentData: {}, // 父节点
			superParent: [], // 上级父节点列表
			treeList: [], // 节点列表
			Extend: [], // 扩展字段
			OpDataInfo: {
				queryFuncName: 'queryTreeData',
				updateFuncName: 'updateTreeData',
				insertFuncName: 'insertTreeData',
				getMaxItemCode: 'treeDataMaxSubItemCode',
				queryRecordsName: 'queryTreeRecords',
				queryTreeTopNode: 'queryTreeTopNode'
			}, // 启动OpDataInfo配置信息'OpData', 和Extend字段同级
			secdLv: {}, // 二级分类
			pageIndex: 0, // 当前页索引
			Hierarchy: 0, // 最大层级
			showEdit: false, // 显示修改/添加表单
			curNode: {}, // 当前选中的节点
			operation: '', // 操作名
			groupIDConfig: {},
			groupID: '',
			query: {},
			// params: 进入页面的查询条件
			params: {
				Level: 1,
				ItemType: '',
				Title: '',
				current: 1,
				limit: 20,
				total: 0
			},
			// paramsParentList: 第一级进入时，为空数组, 当点击“配置下级"时，将本级的参数添加到paramsParentList中。
			// 当返回上级页面时，将最后的一个对象给 params 参数，同时删除掉 paramsParentList 的最后一个对象
			paramsParentList: [],
			useIcon: false
		}
	},
	computed:{
		formatTime2View(){
			return (time)=>{
				return formatTime2View(time)
			}
		}
	},
	async created() {
		this.query = this.$route.query
		await this.queryParentData()
		await this.queryTreeData()
	},
	methods: {
		async queryTreeData() {
			this.params.TreeType = this.treeType
			if (this.groupIDConfig && JSON.stringify(this.groupIDConfig) !== '{}') {
				switch (this.groupIDConfig.getFn) {
					case '1':
						this.groupID = this.params.GroupID = getLocalStorage(this.groupIDConfig.value)
						break
					case '2':
						this.groupID = this.params.GroupID = getVuex(this.groupIDConfig.value)
						break
					case '3':
						this.groupID = this.params.GroupID = getObjAttr(this.query, this.groupIDConfig.value)
						break
					case '4':
						this.groupID = this.params.GroupID = this.groupIDConfig.value
						break
					default:
						break
				}
			}
			const that = this
			httpReqeust.Post(this.OpDataInfo.queryRecordsName, this.params).then((res) => {
				console.log('queryTreeData', res)
				that.params.total = parseInt(res.TotalSize) || 0
				if (res && res.success && res.Records) {
					that.treeList = res.Records
					that.treeList.length &&
						that.treeList.forEach((item) => {
							typeof item.Status === 'boolean' ? item.Status : (item.Status = item.Status === '1')
						})
					for (let i = 0; i < that.treeList.length; i++) {
						for (let j = 0; that.secdLv.Options && j < that.secdLv.Options.length; j++) {
							if (that.treeList[i].ItemType === that.secdLv.Options[j].value) {
								that.treeList[i].secdLvLabel = that.secdLv.Options[j].label
							}
						}
					}
					that.formatExtend()
				} else {
					that.treeList = []
				}
			})
		},
		// 获取扩展字段、二级分类、层级设置
		async queryParentData() {
			// 查询顶级节点
			const res = await httpReqeust.SyncPost(this.OpDataInfo.queryTreeTopNode, { TreeType: this.treeType })
			console.log('topNode: ', res)
			if (res && res.success && res.Records && res.Records.length) {
				this.parentData = res.Records[0]
				// Data字段的格式 {"Extend":[],"Hierarchy":2, OpData:{queryFuncName:'queryTreeData';.......}}
				const Data = JSON.parse(this.parentData.Data.replace(/\\/g, ''))
				this.secdLv = Data.ItemType || ''
				this.Extend = Data.Extend || ''
				this.useIcon = Data.UseIcon || false
				// 定义接口的Key:'OpData'
				this.initOpDataInfo(Data.OpData || '')
				this.parentData.OpDataInfo = this.OpDataInfo
				this.groupIDConfig = Data.getGroupID || {}
				if (Data.Hierarchy) {
					this.Hierarchy = Data.Hierarchy
				} else {
					this.Hierarchy = 0
				}
				// this.Hierarchy = Data.Hierarchy || ''
				// if (typeof this.Hierarchy === 'undefined') {
				//   this.Hierarchy = 0
				// }
				console.log('this.parentData', this.parentData, this.Extend)
			}
		},
		initOpDataInfo(opData) {
			let OpDataInfo = {
				queryFuncName: 'queryTreeData',
				updateFuncName: 'updateTreeData',
				insertFuncName: 'insertTreeData',
				getMaxItemCode: 'treeDataMaxSubItemCode',
				queryRecordsName: 'queryTreeRecords'
			}
			if (opData !== '') {
				if (opData.queryFuncName && opData.queryFuncName.length > 0) {
					OpDataInfo.queryFuncName = opData.queryFuncName
				}
				if (opData.updateFuncName && opData.updateFuncName.length > 0) {
					OpDataInfo.updateFuncName = opData.updateFuncName
				}
				if (opData.insertFuncName && opData.insertFuncName.length > 0) {
					OpDataInfo.insertFuncName = opData.insertFuncName
				}
				if (opData.getMaxItemCode && opData.getMaxItemCode.length > 0) {
					OpDataInfo.getMaxItemCode = opData.getMaxItemCode
				}
				if (opData.queryRecordsName && opData.queryRecordsName.length > 0) {
					OpDataInfo.queryRecordsName = opData.queryRecordsName
				}
			}
			this.OpDataInfo = OpDataInfo
		},
		// 处理扩展字段内容
		formatExtend() {
			let ExtendContent
			for (let i = 0; i < this.Extend.length; i++) {
				if (this.treeList) {
					for (let j = 0; j < this.treeList.length; j++) {
						ExtendContent = JSON.parse(this.treeList[j].Data.replace(/\\/g, ''))
						if (ExtendContent[this.Extend[i].key]) {
							this.treeList[j].ExtendContent = []
							this.treeList[j].ExtendContent.push({
								key: this.Extend[i].key,
								value: ExtendContent[this.Extend[i].key]
							})
						}
					}
				}
			}
		},
		// 管理下级
		ManageSub(child) {
			this.superParent.push(JSON.parse(JSON.stringify(this.parentData)))
			this.paramsParentList.push(JSON.parse(JSON.stringify(this.params)))
			this.parentData = child
			this.parentData.OpDataInfo = this.OpDataInfo
			this.params.Level = parseInt(child.Level) + 1
			this.params.SuperiorItemCode = this.parentData.ItemCode
			this.queryTreeData()
			this.pageIndex++
		},
		// 返回
		goBack() {
			this.parentData = this.superParent[this.superParent.length - 1]
			this.parentData.OpDataInfo = this.OpDataInfo
			this.params = this.paramsParentList[this.paramsParentList.length - 1]
			this.superParent.pop()
			this.paramsParentList.pop()
			this.queryTreeData()
			this.pageIndex--
		},
		// 是否发布
		release(e, row) {
			const params = {}
			params.Status = e ? '1' : '0'
			params.ItemCode = row.ItemCode
			httpReqeust.Post(this.OpDataInfo.updateFuncName, params).then((res) => {
				if (res.success === true && res.data) {
					this.$message({ message: '修改成功', type: 'success' })
				} else {
					this.$message({ message: '修改失败', type: 'error' })
				}
			})
		},
		// 修改节点
		updataNode(row) {
			this.curNode = JSON.parse(JSON.stringify(row))
			this.operation = '修改'
			this.showEdit = true
		},
		// 添加子节点
		addSubNode() {
			this.curNode = {}
			this.operation = '添加'
			this.showEdit = true
		},
		// 隐藏修改/添加表单
		hideEditFn() {
			this.queryTreeData()
			this.showEdit = false
		},
		handleSizeChange(limit) {
			this.params.limit = limit
			this.queryTreeData()
		},
		handleCurrentChange(current) {
			this.params.current = current
			this.queryTreeData()
		},
		// 删除选中节点
		delNode(row) {
			console.log(row)
			this.$confirm(`节点编码：${row.ItemCode}<br>节点名称：${row.Title}`, '确定删除此节点?', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				dangerouslyUseHTMLString: true
			})
				.then(async () => {
					const params = {}
					params.ItemCode = row.ItemCode
					const res = await httpReqeust.SyncPost('delTreeData', params)
					if (res.success) {
						this.$message({
							type: 'success',
							message: '删除成功!'
						})
						this.queryTreeData()
					} else {
						this.$message({
							type: 'error',
							message: '删除失败!'
						})
					}
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					})
				})
		}
	}
}
</script>

<style lang="scss" scoped>
.set {
	margin-right: 15px;
	cursor: pointer;
	font-size: 12px;

	&:nth-child(1) {
		color: #1e9fff;
	}

	&:nth-child(2) {
		color: coral;
	}

	&:nth-child(3) {
		color: red;
	}
}
</style>
